<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition License
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magentocommerce.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Customer
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://www.magentocommerce.com/license/enterprise-edition
 */

/**
 * API2 class for customer (customer)
 *
 * @category   Mage
 * @package    Mage_Customer
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Api2_Customer_Rest_Guest_V1 extends Mage_Customer_Model_Api2_Customer_Rest
{
    /**
     * Is customer has rights to retrieve/update customer item
     *
     * @param int $customerId
     * @throws Mage_Api2_Exception
     * @return bool
     */
    protected function _isOwner($customerId)
    {
        if ($this->getApiUser()->getUserId() !== $customerId) {
            $this->_critical(self::RESOURCE_NOT_FOUND);
        }
        return true;
    }

    /**
     * Create customer
     *
     * @param array $data
     * @return string
     */
    protected function _create(array $data)
    {
        //return $data;
        /** @var $validator Mage_Api2_Model_Resource_Validator_Eav */
        // $validator = Mage::getResourceModel('api2/validator_eav', array('resource' => $this));

        // $data = $validator->filter($data);
        // if (!$validator->isValidData($data)) {
        //     foreach ($validator->getErrors() as $error) {
        //         $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
        //     }
        //     $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
        // }

        /** @var $customer Silk_Zgb_Model_Customer */
        $customer = Mage::getModel('customer/customer');

        if(!$data['firstname'])
        {
            $this->_critical("用户名不能为空!", 101001);
        }

        if (preg_match('/^\d+$/', $data['firstname'])) {
            $this->_critical("用户名不能为纯数字!", 101001);
        }

        if(!$data['lastname'])
        {
            $this->_critical("店铺名不能为空!", 101002);
        }

        if(!$data['mobile'])
        {
            $this->_critical("手机号不能为空!", 101003);
        }

        $websiteId = $this->getParam('website_id');
        if (!$websiteId) {
            $this->_critical("区域信息不能为空!", 101006);
        }

        if (!preg_match("/^[1][34578][0-9]{9}$/", $data['mobile'])) {
            $this->_critical("请输入正确的手机号码！", Mage_Api2_Model_Resource::ERROR_CUSTOMER_MOBILE_ERROR);
        }


        if ($customer->customerFirstnameExists($data['firstname'])) {
            $this->_critical("用户名已存在!", 101004);
        }

        if ($customer->customerMobileExists($data['mobile'])) {
            $this->_critical("手机号已存在!", 101005);
        }


        $customer->setWebsiteId($websiteId);
        $customer->setFirstname($data['firstname']);
        $customer->setLastname($data['lastname']);
        $customer->setMobile($data['mobile']);
        $customer->setEmail($data['mobile']."@hahahui.cn");
        $customer->setPassword($data['password']);

        //$customer->setData($data);
        $request = $this->getRequest();
        $token = Mage::getModel('mapi/token');
        try {
            //$customer->save();
            $customer->setWebsiteId($websiteId)->save();
            Mage::dispatchEvent('customer_register_success',
                array('account_controller' => $this, 'customer' => $customer)
            );
            $token->setCustomerId($customer->getId());
            $token->setWebsiteId($customer->getWebsiteId());
            $token->setAppId($request->getHeader('App-Id'));
            $token->setDeviceId($request->getHeader('Device-Id'));
            $token->save();
        } catch (Mage_Core_Exception $e) {
            $this->_critical($e->getMessage(), 101007);
            //$this->_error($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
        } catch (Exception $e) {
            $this->_critical($e->getMessage(), 101008);
            //$this->_critical(self::RESOURCE_INTERNAL_ERROR);
        }

        $result = array(
            'customer_id' => $customer->getId(),
            'firstname' => $customer->getFirstname(),
            'lastname' => $customer->getLastname(),
            'mobile' => $customer->getMobile(),
            'access_token' => $token->getToken(),
            'access_token_secret' => $token->getTokenSecret()
        );

        return $result;
    }

    /**
     * Retrieve information about customer
     *
     * @throws Mage_Api2_Exception
     * @return array
     */
    protected function _retrieve()
    {
        if ($this->_isOwner($this->getRequest()->getParam('id'))) {
            return parent::_retrieve();
        }
    }

    /**
     * Retrieve collection with only current customer instance
     *
     * @return Mage_Customer_Model_Resource_Customer_Collection
     */
    protected function _getCollectionForRetrieve()
    {
        return parent::_getCollectionForRetrieve()->addAttributeToFilter('entity_id', $this->getApiUser()->getUserId());
    }

    /**
     * Update customer
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _update(array $data)
    {
//        if ($this->_isOwner($this->getRequest()->getParam('id'))) {
//            parent::_update($data);
//        }
        //return $data;
        if ($mobile = $this->getParam('mobile')) {
            if (!preg_match("/^[1][34578][0-9]{9}$/", $mobile)) {
                $this->_critical('手机号码格式不正确！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_MOBILE_FORMAT_ERROR);
            }

            /** @var Mage_Customer_Model_Customer $customerModel */
            $customerModel = Mage::getModel('customer/customer');
            $email = "{$mobile}@hahahui.cn";
            $collection = $customerModel->getCollection()->addAttributeToFilter('email', array('eq' => $email));
            $item = $collection->getFirstItem();

            if (!$item || !$item->getId()) {
                $this->_critical('当前用户不存在！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_NOT_FOUND);
            }

            $customer = $customerModel
                ->setWebsiteId($item->getWebsiteId())
                ->loadByEmail($email);

            $newPassword = $data['new_password'];
            $confirmation = $data['conformation'];

            if (strlen($newPassword) < 6 || strlen($newPassword) > 20)
                $this->_critical("请输入6~20位的密码!", Mage_Api2_Model_Resource::ERROR_CUSTOMER_PASSWORD_LENGTH);

            if ($newPassword != $confirmation)
            {
                $this->_critical("两次输入的密码不相同!{$newPassword}-{$confirmation}", Mage_Api2_Model_Resource::ERROR_CUSTOMER_PASSWORD_NOT_MATCH);
            }

            $cache = Mage::app()->getCache();
            $captchaSaved = $cache->load('CAPTCHA_'.$mobile);
            if (!$captchaSaved)
                $this->_critical("请先获取验证码!", Mage_Api2_Model_Resource::ERROR_CAPTCHA_NEED);

            if ($this->getParam('captcha') != $captchaSaved) {
                $attemptTimes = $cache->load('CAPTCHA_TIMES_'.$mobile);

                if (!$attemptTimes) $attemptTimes = 1;
                if ($attemptTimes >= 3) {
                    $cache->remove('CAPTCHA_'.$mobile);
                    $cache->remove('CAPTCHA_TIMES_'.$mobile);
                    $this->_critical("已经输错了3次验证码，请重新获取!", Mage_Api2_Model_Resource::ERROR_CAPTCHA_NEED_RESEND);
                }
                $cache->save((string)($attemptTimes + 1), 'CAPTCHA_TIMES_'.$mobile, array('QSLB_CAPTCHA'), 600);
                $this->_critical("验证码错误!", Mage_Api2_Model_Resource::ERROR_CAPTCHA_NOT_MATCH);
            }

            try {
                $customer->setPassword($newPassword);
                $customer->save();
                $cache->remove('CAPTCHA_'.$mobile);
                $cache->remove('CAPTCHA_TIMES_'.$mobile);
            } catch (Exception $e) {
                $this->_critical($e->getMessage(), Mage_Api2_Model_Resource::ERROR_ACCOUNT_UNKNOWN_ERROR);
            }

            return array();
        } else {
            $this->_critical('请输入手机号码！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_MOBILE_EMPTY);
        }
    }

    /**
     * Update customers
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _multiUpdate(array $data)
    {
        $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED, Mage_Api2_Model_Server::HTTP_FORBIDDEN);
    }
}
